// 管理员
'use strict';
const Service = require('egg').Service;
const { Op } = require('sequelize');
const { failRes, successRes } = require('../extend/helper');
const { Journal } = require('../exception/Journal');
function toInt (str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}
class sAdmin extends Service {
  // pc
  // 管理员登录
  async pc_s_login (params = {}) {
    let response = null;
    const { ctx, app } = this;
    try {
      const { account, password } = params;
      const result = await ctx.model.Admin.findOne({
        where: { username: account, password }
      })
      console.log('result: ', result);
      if (result && result.id && (result.state === 1)) {
        const expiresIn = 60 * 60 * 24 * 1000;
        // 生成Token
        const token = app.jwt.sign({
          id: result.id,
          username: account,	// 需要存储的Token数据
        }, app.config.jwt.secret, {
          expiresIn, // 有效期时间
        });
        await ctx.model.Admin.update(
          { token },
          { where: { id: result?.id } }
        );
        await Journal(ctx, { params: { account }, operatorType: '后台系统 -> 登录', code: 200 });
        response = successRes({
          idCode: result?.id ?? '',
          account: result?.username ?? '',
          failure_time: Math.floor(Date.now() / 1000) + expiresIn,
          token
        })
      } else if (result && result.state === 0) {
        await Journal(ctx, { params: { account }, operatorType: '后台系统 -> 登录', code: 105 });
        response = failRes(105);
      } else {
        await Journal(ctx, { params: { account }, operatorType: '后台系统 -> 登录', code: 104 });
        response = failRes(104);
      }
    } catch (error) {
      console.error(error, '<---- error - 后台系统 -> 登录');
      await Journal(ctx, { operatorType: '后台系统 -> 登录', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 查
  async pc_s_query (params) {
    // console.log('params: ', params);
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);
      const username = params?.username ?? '';
      const state = (params?.state ?? '') || '';
      let whereMap = {
        username: {
          [Op.like]: `%${username}%`
        },
        state
      }
      if (state === '') {
        whereMap = {
          username: {
            [Op.like]: `%${username}%`
          }
        }
      }
      // console.log('state: ', state);
      const result = await ctx.model.Admin.findAndCountAll({
        where: whereMap,
        order: [['id', 'DESC']], // 排序
        attributes: ['id', 'username', 'password', 'state', 'createdAt', 'updatedAt'],
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      })
      await Journal(ctx, { operatorType: '账号管理 -> 查询', code: 200 });
      response = successRes({
        records: (result?.rows ?? []),
        total: (result?.count ?? 0),
        pageSize,
        currentPage
      });
    } catch (error) {
      console.error(error, '<---- error - 账号管理查询');
      await Journal(ctx, { operatorType: '账号管理 -> 查询', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 增加管理员账户
  async pc_s_create (params) {
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.Admin.create(
        params,
        { attributes: { extends: ['id', 'username', 'password', 'state'] } } // 向数据库插入特定字段
      );
      await Journal(ctx, { operatorType: '账号管理 -> 新增', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 账号管理新增');
      await Journal(ctx, { operatorType: '账号管理 -> 新增', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 改
  async pc_s_update (params) {
    let response = null;
    try {
      const { ctx } = this;
      await ctx.model.Admin.update(
        params,
        {
          where: { id: params.id },
          attributes: { extends: ['id'] }
        }
      );
      await Journal(ctx, { operatorType: '账号管理 -> 编辑', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 账号管理编辑');
      await Journal(ctx, { operatorType: '账号管理 -> 编辑', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 删
  async pc_s_delete (params) {
    let response = null;
    try {
      const { ctx } = this;
      await ctx.model.Admin.destroy(
        {
          where: { id: params.id },
        }
      );
      await Journal(ctx, { operatorType: '账号管理 -> 删除', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 账号管理删除');
      await Journal(ctx, { operatorType: '账号管理 -> 删除', code: 401 });
      response = failRes(401);
    }
    return response;
  }
}

module.exports = sAdmin;
